<template>
  <el-card class="container-card">
    <el-form label-width="90px" :model="sku" :rules="rules" ref="form">
      <el-form-item label="SPU名称">
        <span>{{ spu.spuName }}</span>
      </el-form-item>
      <el-form-item label="SKU名称" prop="skuName">
        <el-input placeholder="请输入SKU名称" v-model="sku.skuName"> </el-input>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input-number
          class="sku-input-number"
          controls-position="right"
          :min="1"
          v-model="sku.price"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="重量" prop="weight">
        <el-input-number
          class="sku-input-number"
          controls-position="right"
          :min="1"
          v-model="sku.weight"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="SKU描述" prop="skuDesc">
        <el-input
          type="textarea"
          :rows="3"
          placeholder="请输入SKU描述"
          v-model="sku.skuDesc"
        >
        </el-input>
      </el-form-item>

      <el-form-item label="平台属性">
        <el-row>
          <el-col
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            v-for="(attr, index) in attrList"
            :key="attr.Id"
            class="sku-row-col"
          >
            <el-form-item :label="attr.attrName">
              <el-select
                v-model="sku.skuAttrValueList[index]"
                :placeholder="`请选择${attr.attrName}`"
                filterable
                clearable
                default-first-option
              >
                <el-option
                  v-for="attrValue in attr.attrValueList"
                  :key="attrValue.id"
                  :label="attrValue.valueName"
                  :value="
                    `${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`
                  "
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-row>
          <el-col
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            v-for="(spuSaleAttr, index) in spu.spuSaleAttrList"
            :key="spuSaleAttr.Id"
            class="sku-row-col"
          >
            <el-form-item :label="spuSaleAttr.saleAttrName">
              <el-select
                v-model="sku.skuSaleAttrValueList[index]"
                :placeholder="`请选择${spuSaleAttr.saleAttrName}`"
                filterable
                clearable
                default-first-option
              >
                <el-option
                  v-for="spuSaleAttrValue in spuSaleAttr.spuSaleAttrValueList"
                  :key="spuSaleAttrValue.id"
                  :label="spuSaleAttrValue.saleAttrValueName"
                  :value="
                    `${spuSaleAttr.id}:${spuSaleAttr.saleAttrName}:${spuSaleAttrValue.id}:${spuSaleAttrValue.saleAttrValueName}`
                  "
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="SKU图片">
        <el-table
          :data="spuImageList"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="图片" prop="imgUrl">
            <template v-slot="{ row }">
              <img class="spu-img" :src="row.imgUrl" :alt="row.imgName" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName" />
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-button
                :type="row.isDefault === '1' ? 'success' : 'primary'"
                size="mini"
                round
                :disabled="row.isDefault === '1' ? true : false"
                @click="setDefaultImage(row)"
              >
                {{ row.isDefault === '1' ? '默认图片' : '设置默认图片' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveSkuInfo">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { reqAttrList } from '@/api/product/attr'
import {
  reqSpuById,
  reqSpuImageListById,
  reqSaveSkuInfo
} from '@/api/product/spu'
import { mapState } from 'vuex'
export default {
  name: 'AddSKU',
  data() {
    return {
      spu: {},
      sku: {
        price: 0,
        weight: 0,
        skuAttrValueList: [],
        skuDefaultImg: '',
        skuDesc: '',
        skuImageList: [],
        skuName: '',
        skuSaleAttrValueList: []
      },
      attrList: [],
      spuImageList: [],
      rules: {
        skuName: [
          { required: true, message: '请输入SKU名称', trigger: 'blur' }
        ],
        skuDesc: [
          { required: true, message: '请输入SKU描述', trigger: 'blur' }
        ],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        weight: [{ required: true, message: '请输入重量', trigger: 'blur' }]
      }
    }
  },
  async mounted() {
    const { spuId, category1Id, category2Id, category3Id } = this
    const [attrListRes, spuRes, spuImageListRes] = await Promise.allSettled([
      reqAttrList({ category1Id, category2Id, category3Id }),
      reqSpuById(spuId),
      reqSpuImageListById(spuId)
    ])
    attrListRes.status === 'fulfilled'
      ? (this.attrList = attrListRes.value)
      : this.$message.error('获取平台属性失败')
    spuRes.status === 'fulfilled'
      ? (this.spu = spuRes.value)
      : this.$message.error('获取SPU信息失败')
    if (spuImageListRes.status === 'fulfilled') {
      this.spuImageList = spuImageListRes.value.map(spuImage => {
        return {
          ...spuImage,
          isDefault: '0'
        }
      })
    } else {
      this.$message.error('获取SPU信息失败')
    }
  },
  methods: {
    handleSelectionChange(selects) {
      this.sku.skuImageList = selects
    },
    setDefaultImage(row) {
      this.spuImageList.forEach(spuImage => {
        spuImage.isDefault = '0'
      })
      row.isDefault = '1'
    },
    cancel() {
      this.$emit('updateShow', 1)
    },
    saveSkuInfo() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const {
            price,
            weight,
            skuAttrValueList,
            skuDesc,
            skuImageList,
            skuName,
            skuSaleAttrValueList
          } = this.sku
          const { spuId, category3Id } = this
          const data = {
            category3Id,
            price,
            skuAttrValueList: skuAttrValueList
              .filter(Boolean)
              .map(skuAttrValue => {
                const [
                  attrId,
                  attrName,
                  valueId,
                  valueName
                ] = skuAttrValue.split(':')
                return {
                  attrId,
                  attrName,
                  valueId,
                  valueName
                }
              }),
            skuDefaultImg: skuImageList.find(
              skuImage => skuImage.isDefault === '1'
            ).imgUrl,
            skuDesc,
            skuImageList,
            skuName,
            skuSaleAttrValueList: skuSaleAttrValueList
              .filter(Boolean)
              .map(skuSaleAttrValue => {
                const [
                  saleAttrId,
                  saleAttrName,
                  saleAttrValueId,
                  saleAttrValueName
                ] = skuSaleAttrValue.split(':')
                return {
                  saleAttrId,
                  saleAttrName,
                  saleAttrValueId,
                  saleAttrValueName
                }
              }),
            spuId,
            weight
          }
          await reqSaveSkuInfo(data)
          this.$message.success('添加SKU成功')
          this.cancel()
        }
      })
    }
  },
  computed: {
    ...mapState('spu', ['spuId']),
    ...mapState('category', ['category1Id', 'category2Id', 'category3Id'])
  }
}
</script>

<style lang="scss" scoped>
.sku-input-number {
  width: 100%;
}
.sku-row-col {
  margin-bottom: 15px;
}
.spu-img {
  width: 100px;
  height: 100px;
}
</style>
